package com.modifiertech.lineage.client.gui.ftbint;

import com.feed_the_beast.ftblib.lib.gui.*;
import com.feed_the_beast.ftblib.lib.icon.Color4I;
import com.feed_the_beast.ftblib.lib.icon.Icon;
import com.feed_the_beast.ftblib.lib.util.misc.MouseButton;
import com.modifiertech.lineage.BaseConst;
import com.modifiertech.lineage.Lineage;
import com.modifiertech.lineage.LineageRegistries;
import com.modifiertech.lineage.api.PlayerData;
import com.modifiertech.lineage.api.PlayerDataSkill;
import com.modifiertech.lineage.commands.CmdHelper;
import com.modifiertech.lineage.event.PlayerDataHandler;
import com.modifiertech.lineage.handler.SkillLevelUpHandler;
import com.modifiertech.lineage.network.MessageAttributeModify;
import com.modifiertech.lineage.network.MessageSkillModify;
import com.modifiertech.lineage.network.NetworkHandler;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.text.TextComponentString;
import net.minecraftforge.fml.common.FMLCommonHandler;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class PanelSkillDescV2 extends Panel {
    private PanelSkillV2 panelSkillV2;
    private TextField textFieldSkillPointTotal;
    private TextField textFieldSkillPointTotalValue;
    private TextField textFieldSkillPointDistributed;
    private TextField textFieldSkillPointDistributedValue;
    private LevelChangeAcceptBtn acceptLevelChange;
    public PlayerData playerDataRelClient;
    private GuiLineageV2 mainGui;
    private List<SkillShortCutBtn> skillShortCutBtnList=new ArrayList<>();


    public PanelSkillDescV2(Panel panel,GuiLineageV2 mainGui,PanelSkillV2 panelSkillV2) {
        super(panel);
        this.panelSkillV2=panelSkillV2;
        this.mainGui=mainGui;
        initialize();
    }


    /**判断是否在设定快捷键场景
     *
     * @return
     */
    public boolean ifSkillLookingFor(){
        return skillShortCutBtnList.stream().filter(h->h.lookingFor).findAny().isPresent();
    }



    public void initialize() {
        initPlayerData();
        initAttrString();
        initOptBtn();
        initSkillShortBtn();
    }

    private void initSkillShortBtn() {
        //TODO 此处与UI布局有关.
        int skillShortCount=8;
        PlayerData data = PlayerDataHandler.get(Lineage.proxy.getClientPlayer());

        for (int i = 0; i < skillShortCount; i++) {
            //按当前nbt存储快捷绑定进行渲染
            PlayerDataSkill temp= null;
            temp = data.getPlayerDataShortCutTag().getShortCutRelSkill().get(i+"");
            SkillShortCutBtn skillShortCutBtn = new SkillShortCutBtn(this,this,i);
            if (null!=temp){
                skillShortCutBtn.setAssignSkillName(temp.getSkillName());
                skillShortCutBtn.setTitle(temp.getSkillName());
                skillShortCutBtn.setIcon(temp.getIcon());
            }
            skillShortCutBtnList.add(skillShortCutBtn);

        }
    }

    private void initOptBtn() {
        //accept skill change
        acceptLevelChange=new LevelChangeAcceptBtn(this);
    }

    /**按钮：技能升级确认
     *
     */
    public class LevelChangeAcceptBtn extends SimpleButton {

        public LevelChangeAcceptBtn(Panel panel) {
            super(panel,"确认升级",GuiIconsV2.ACCEPT,(k,v)->{});
//            this.icon=GuiIconsV2.ACCEPT;
//            this.title="确认升级";
        }
        @Override
        public void onClicked(MouseButton button) {
//            PlayerData data = PlayerDataHandler.get(Lineage.proxy.getClientPlayer());
            //get all skill opt
            //客户端无需获取服务端用户
//            EntityPlayerMP playerMP=
//                    FMLCommonHandler.instance().getMinecraftServerInstance()
//                            .getPlayerList().getPlayerByUsername(Lineage.proxy.getClientPlayer().getName());
            MessageSkillModify messageSkillModify=new MessageSkillModify();
            for (BtnSkillV2 skillButton : ((PanelSkillV2) mainGui.getPanelSkillV2w().getInnerPanelRel())
                    .getSkillButtons()) {
                if(skillButton.getRelPanelSkill().hasSkillInTemp(skillButton.skillInfo.getSkillName())){
                    String skillName=skillButton.skillInfo.getSkillName();
                    int skillToAdd=skillButton.getRelPanelSkill().getSkillTempCount().get(skillName);
                    messageSkillModify.write(skillName, BaseConst.SkillOperate.up,skillToAdd);
                }
            }
            //通讯
            //FIXME 打印日志表达发出事件
            NetworkHandler.INSTANCE.sendToServer(messageSkillModify);
            //客户端操作缓存
            panelSkillV2.clearSkillTempMap();//FIXME 缓存意义不明
//            ((PanelSkillV2) mainGui.getPanelSkillV2w().getInnerPanelRel())
//                    .getSkillButtons().stream().forEach(
//                            h->h.renderRelLevelText());
        }

        @Override
        public boolean shouldDraw() {
            if(panelSkillV2.skillInTempTotal()>0)return true;
            return false;
        }

        @Override
        public boolean isEnabled() {
            return shouldDraw();
        }
    }


    public List<SkillShortCutBtn> getSkillShortCutBtnList() {
        return skillShortCutBtnList;
    }

    private void initAttrString() {
        PlayerData data = PlayerDataHandler.get(Lineage.proxy.getClientPlayer());
        //skill point total
        textFieldSkillPointTotal=new TextField(this);
        textFieldSkillPointTotal.setPosAndSize(5,5,20,5);
        textFieldSkillPointTotal.setText("TotalPoint");
        textFieldSkillPointTotalValue=new TextField(this);
        textFieldSkillPointTotalValue.setPosAndSize(70,5,20,5);
        textFieldSkillPointTotalValue.setText(data.getSkillPointTotal()+"");
        //skill point undistribute
        textFieldSkillPointDistributed =new TextField(this);
        textFieldSkillPointDistributed.setPosAndSize(5,15,20,5);
        textFieldSkillPointDistributed.setText("LeftPoint");
        textFieldSkillPointDistributedValue =new TextField(this);
        textFieldSkillPointDistributedValue.setPosAndSize(70,15,20,5);
        textFieldSkillPointDistributedValue.setText(data.getSkillPointUndistributed()+"");

    }

    private void initPlayerData() {
        this.playerDataRelClient = PlayerDataHandler.get(Lineage.proxy.getClientPlayer());
    }

    @Override
    public void addWidgets() {
        add(textFieldSkillPointTotal);
        add(textFieldSkillPointDistributed);
        add(textFieldSkillPointTotalValue);
        add(textFieldSkillPointDistributedValue);
        add(acceptLevelChange);
        addAll(skillShortCutBtnList);

    }

    @Override
    public void alignWidgets() {
        acceptLevelChange.setPosAndSize(width-30,height-30,25,25);
        //=============布局技能快捷栏==
        int eachHeight=20;
        int eachWeight=20;
        int baseX=5;
        int baseY=30;
        int stepX=eachWeight+5;
        int stepY=eachHeight+5;
        //TODO 此处快捷技能栏与UI有绑定,UI提供8个技能栏
        int maxCountForColumn=4;
        int maxCountForRow=2;
        //
        int index=0;
        for (int currentColumn = 0; currentColumn < maxCountForColumn; currentColumn++) {
            for (int currentRow = 0; currentRow < maxCountForRow; currentRow++) {
                //
                skillShortCutBtnList.get(index)
                        .setPosAndSize(baseX+(currentColumn)*stepX,baseY+(currentRow)*stepY,eachWeight,eachHeight);
                //
                index++;
            }
        }
    }

    @Override
    public void tick() {
        super.tick();
        //render attribute
        renderAttribute();
    }


    private void renderAttribute() {
        PlayerData data = PlayerDataHandler.get(Lineage.proxy.getClientPlayer());
        if(null!=data){
            //Total skill point
            this.getTextFieldSkillPointTotalValue().setText(data.getSkillPointTotal()+"");
            //Undistributed skill point
            int pointleft=data.getSkillPointUndistributed()-panelSkillV2.skillInTempTotal();
            String prefix="";
            if(pointleft>0){
                prefix="§6§l";
            }
            this.getTextFieldSkillPointDistributedValue().setText(prefix+pointleft);
        }
    }

    @Override
    public void drawBackground(Theme theme, int x, int y, int w, int h) {
//        theme.drawPanelBackground(x, y, w, h);
        Color4I.WHITE.withAlpha(30).withBorder(Color4I.BLACK,true).draw(x, y, w, h);
    }

    public TextField getTextFieldSkillPointTotal() {
        return textFieldSkillPointTotal;
    }

    public void setTextFieldSkillPointTotal(TextField textFieldSkillPointTotal) {
        this.textFieldSkillPointTotal = textFieldSkillPointTotal;
    }

    public TextField getTextFieldSkillPointTotalValue() {
        return textFieldSkillPointTotalValue;
    }

    public void setTextFieldSkillPointTotalValue(TextField textFieldSkillPointTotalValue) {
        this.textFieldSkillPointTotalValue = textFieldSkillPointTotalValue;
    }

    public TextField getTextFieldSkillPointDistributed() {
        return textFieldSkillPointDistributed;
    }

    public void setTextFieldSkillPointDistributed(TextField textFieldSkillPointDistributed) {
        this.textFieldSkillPointDistributed = textFieldSkillPointDistributed;
    }

    public TextField getTextFieldSkillPointDistributedValue() {
        return textFieldSkillPointDistributedValue;
    }

    public void setTextFieldSkillPointDistributedValue(TextField textFieldSkillPointDistributedValue) {
        this.textFieldSkillPointDistributedValue = textFieldSkillPointDistributedValue;
    }

    /**技能快捷键按钮
     *
     */
    public class SkillShortCutBtn extends SimpleButton{

        //上层技能关联对象
        private PanelSkillDescV2 rel;

        private boolean lookingFor=false;
        private int index;
        private String assignSkillName=null;


        public int getIndex() {
            return index;
        }

        public void setIndex(int index) {
            this.index = index;
        }


        public boolean isLookingFor() {
            return lookingFor;
        }

        public void setLookingFor(boolean lookingFor) {
            this.lookingFor = lookingFor;
        }

        public SkillShortCutBtn(Panel panel, PanelSkillDescV2 rel,int index) {
            super(panel,"空",GuiIconsV2.skillChoiceEmpty,(k,v)->{});
            this.index=index;
            this.rel=rel;
        }

        public String getAssignSkillName() {
            return assignSkillName;
        }

        public void setAssignSkillName(String assignSkillName) {
            this.assignSkillName = assignSkillName;
        }

//        public SkillShortCutBtn(Panel panel, String t, Icon i) {
//            super(panel, t, i);
//        }

        @Override
        public void onClicked(MouseButton button) {
            boolean assignSkillNameEmpty = false;
            assignSkillNameEmpty = null==assignSkillName;
            //0.右键进行渲染点中技能解释
            if(button.isRight()){
                mainGui.getPanelFootV2w().setSkillDescription(BtnSkillV2.buildDescString(
                        null==this.assignSkillName?null:
                                playerDataRelClient.getPlayerDataSkillByName(assignSkillName).get()
                        ,playerDataRelClient));
            }else{
                //1.点选中的技能再次点击,恢复至未选中状态
                if (this.icon.equals(GuiIconsV2.skillChoosing)){
                    lookingFor=false;
                    this.setIcon(GuiIconsV2.skillChoiceEmpty);
                    mainGui.addLineToConsolePanel("§4离开快捷键编辑模式.");
                    return;
                }
                //其他情况先清空非指定技能选中的 快捷释放栏
                rel.getSkillShortCutBtnList().stream().filter(h->h.assignSkillName==null).forEach(
                        h->{
                            h.setIcon(GuiIconsV2.skillChoiceEmpty);
                            h.setAssignSkillName(null);
                            h.setLookingFor(false);
                            h.setTitle("空");
                        });
                this.setIcon(GuiIconsV2.skillChoosing);
                this.setLookingFor(true);
                this.setAssignSkillName(null);
                this.setTitle("空");
                //消息:清理对应快捷键技能绑定.
                if (!assignSkillNameEmpty){
                    MessageSkillModify messageSkillModify  = new MessageSkillModify();
                    messageSkillModify.writeClearTag(this.getIndex());
                    //消息同步:清理对应快捷键技能绑定.
                    NetworkHandler.INSTANCE.sendToServer(messageSkillModify);
                }
                mainGui.addLineToConsolePanel("进入快捷键编辑模式,焦点 [快捷键 "+this.getIndex()+"]");
            }

        }
    }


}
